package ve.lm.hrms_cy.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ve.lm.hrms_cy.Entity.Bill;
import ve.lm.hrms_cy.Entity.Department;
import ve.lm.hrms_cy.Entity.Employee;
import ve.lm.hrms_cy.Entity.Request.BillQueryRequest;
import ve.lm.hrms_cy.Entity.Request.SalaryQueryRequest;
import ve.lm.hrms_cy.Entity.Response.ResponseEntityCY;
import ve.lm.hrms_cy.Entity.Salary;
import ve.lm.hrms_cy.Mapper.BillMapper;
import ve.lm.hrms_cy.Mapper.DepartmentMapper;
import ve.lm.hrms_cy.Mapper.EmployeeMapper;
import ve.lm.hrms_cy.Mapper.SalaryMapper;

import java.util.Optional;

@Service
public class MoneyManagerService {


    @Autowired
    SalaryMapper salaryMapper;

    @Autowired
    BillMapper billMapper;

    @Autowired
    EmployeeMapper employeeMapper;

    @Autowired
    DepartmentMapper departmentMapper;


    public ResponseEntityCY<Boolean> addSalary(Salary salary) {

        // 1. 判断是否已有该职工薪资记录
        LambdaQueryWrapper<Salary> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Salary::getEmployeeId, salary.getEmployeeId());

        Salary existing = salaryMapper.selectOne(lambdaQueryWrapper);
        if (existing != null) {
            return new ResponseEntityCY<>("409", false, false, "该职工已存在薪资记录！");
        }

        // 2. 自动分配主键 ID（最大值 + 1）
        Long maxId = Optional.ofNullable(
                salaryMapper.selectList(null)
                        .stream()
                        .map(Salary::getId)
                        .max(Long::compareTo)
                        .orElse(0L)
        ).orElse(0L);
        salary.setId(maxId + 1);

        Employee findEmployee = employeeMapper.selectById(salary.getEmployeeId());

        if(findEmployee==null)
            return new ResponseEntityCY<>("400",false,false,"未能查询到该职工！");

        salary.setDepartment(findEmployee.getDepartment());
        salary.setPhoneNumber(findEmployee.getPhoneNumber());

        // 3. 设置默认状态
        salary.setStatus("正常");

        // 4. 插入记录
        int row = salaryMapper.insert(salary);
        if (row > 0) {
            return new ResponseEntityCY<>("200", true, true, "薪资添加成功！");
        }

        return new ResponseEntityCY<>("500", false, false, "在可添加情况下出现未知错误！");
    }

    public ResponseEntityCY<IPage<Salary>> findSalaryByPage(SalaryQueryRequest request) {
        LambdaQueryWrapper<Salary> queryWrapper = new LambdaQueryWrapper<>();
        Page<Salary> page = new Page<>(request.getCurrent(), request.getSize());

        if (request.getEmployeeId() != null) {
            queryWrapper.eq(Salary::getEmployeeId, request.getEmployeeId());
        }

//        if (request.getName() != null) {
//            queryWrapper.like(Salary::getDepartment, request.getName()) ;// 若要模糊查姓名，应连接职工表；这里只查 department
//
//        }

        if (request.getDepartment() != null) {
            queryWrapper.like(Salary::getDepartment, request.getDepartment());
        }


        return new ResponseEntityCY<>("200", true, salaryMapper.selectPage(page, queryWrapper), "成功查询薪资信息！");
    }

    public ResponseEntityCY<Boolean> updateSalary(Salary salary) {
        Salary existing = salaryMapper.selectById(salary.getId());

        if (existing == null) {
            return new ResponseEntityCY<>("400", false, true, "未能发现该薪资记录！");
        }

        int row = salaryMapper.updateById(salary);
        if (row > 0) {
            return new ResponseEntityCY<>("200", true, true, "成功更新薪资信息！");
        }

        return new ResponseEntityCY<>("500", true, true, "在更新薪资可行的情况下出现未知错误！");
    }


    public ResponseEntityCY<Boolean> deleteOrRecoverSalary(Long id, Boolean isDelete) {
        Salary salary = salaryMapper.selectById(id);

        if (salary == null) {
            return new ResponseEntityCY<>("400", false, false, "未能发现该薪资记录！");
        }

        if ("注销".equals(salary.getStatus()) && isDelete) {
            return new ResponseEntityCY<>("400", false, true, "该薪资记录已被注销！");
        }

        if ("正常".equals(salary.getStatus()) && !isDelete) {
            return new ResponseEntityCY<>("400", false, true, "该薪资记录已处于正常状态！");
        }

        salary.setStatus(isDelete ? "注销" : "正常");
        int row = salaryMapper.updateById(salary);

        if (row > 0 && isDelete) {
            return new ResponseEntityCY<>("200", true, true, "成功注销该薪资记录！");
        } else if (row > 0) {
            return new ResponseEntityCY<>("200", true, true, "成功恢复该薪资记录！");
        } else {
            return new ResponseEntityCY<>("500", false, false, "在操作薪资记录时出现未知错误！");
        }
    }

    public ResponseEntityCY<Boolean> addBill(Bill bill) {

        // 1. 查询该部门是否存在（根据 departmentId）
        Department findDepartment = departmentMapper.selectById(bill.getDepartmentId());
        if (findDepartment == null) {
            return new ResponseEntityCY<>("400", false, false, "未能查询到该部门！");
        }

        // 2. 自动分配主键 ID（最大值 + 1）
        Long maxId = Optional.ofNullable(
                billMapper.selectList(null)
                        .stream()
                        .map(Bill::getId)
                        .max(Long::compareTo)
                        .orElse(0L)
        ).orElse(0L);
        bill.setId(maxId + 1);

        // 3. 设置账单中的部门名称（department 字段）
        bill.setDepartment(findDepartment.getName());

        // 4. 插入账单记录
        int row = billMapper.insert(bill);
        if (row > 0) {
            return new ResponseEntityCY<>("200", true, true, "账单添加成功！");
        }

        return new ResponseEntityCY<>("500", false, false, "在可添加情况下出现未知错误！");
    }


    public ResponseEntityCY<IPage<Bill>> findBillByPage(BillQueryRequest request) {
        LambdaQueryWrapper<Bill> queryWrapper = new LambdaQueryWrapper<>();
        Page<Bill> page = new Page<>(request.getCurrent(), request.getSize());


        if (request.getId() != null) {
            queryWrapper.eq(Bill::getId, request.getId());
        }


        if (request.getDepartment() != null && !request.getDepartment().isEmpty()) {
            queryWrapper.like(Bill::getDepartment, request.getDepartment());
        }


        return new ResponseEntityCY<>("200", true, billMapper.selectPage(page, queryWrapper), "成功查询账单信息！");
    }



    public ResponseEntityCY<Boolean> updateBill(Bill bill) {
        // 1. 查询是否存在此账单记录
        Bill existing = billMapper.selectById(bill.getId());
        if (existing == null) {
            return new ResponseEntityCY<>("400", false, true, "未能发现该账单记录！");
        }

        // 2. 校验部门 ID 是否有效
        Department department = departmentMapper.selectById(bill.getDepartmentId());
        if (department == null) {
            return new ResponseEntityCY<>("400", false, true, "部门ID无效，未能找到对应部门！");
        }

        // 3. 更新部门名称
        bill.setDepartment(department.getName());

        // 4. 执行更新
        int row = billMapper.updateById(bill);
        if (row > 0) {
            return new ResponseEntityCY<>("200", true, true, "成功更新账单信息！");
        }

        // 5. 异常情况返回
        return new ResponseEntityCY<>("500", true, true, "在更新账单可行的情况下出现未知错误！");
    }

    public ResponseEntityCY<Boolean> deleteOrRecoverBill(Long id, Boolean isDelete) {
        Bill bill = billMapper.selectById(id);

        if (bill == null) {
            return new ResponseEntityCY<>("400", false, false, "未能发现该账单记录！");
        }

        // 如果已是“注销”状态却再次注销
        if ("注销".equals(bill.getStatus()) && isDelete) {
            return new ResponseEntityCY<>("400", false, true, "该账单记录已被注销！");
        }

        // 如果当前是“支出”或“支入”状态，却尝试恢复为“支出/支入”但系统不知原始状态
        if (!"注销".equals(bill.getStatus()) && !isDelete) {
            return new ResponseEntityCY<>("400", false, true, "该账单记录已处于活动状态！");
        }

        // 注销处理
        if (isDelete) {
//            System.out.println("B");
            bill.setStatus("注销");
        } else {
            // 默认恢复为“支出”状态（你也可以改成“支入”，或者设计一个 statusBackup 字段）

//            System.out.println("A");
            bill.setStatus("支入");     //恢复bug
        }

        int row = billMapper.updateById(bill);

        if (row > 0 && isDelete) {
            return new ResponseEntityCY<>("200", true, true, "成功注销该账单记录！");
        } else if (row > 0) {
            return new ResponseEntityCY<>("200", true, true, "成功恢复该账单记录！");
        } else {
            return new ResponseEntityCY<>("500", false, false, "在操作账单记录时出现未知错误！");
        }
    }

}
